package net.dreamlu.assets.ui.jfinal;

import java.io.Writer;

import com.jfinal.template.Directive;
import com.jfinal.template.Env;
import com.jfinal.template.expr.ast.Const;
import com.jfinal.template.expr.ast.Expr;
import com.jfinal.template.expr.ast.ExprList;
import com.jfinal.template.stat.ParseException;
import com.jfinal.template.stat.Scope;

import net.dreamlu.assets.utils.AssetsUtils;

public class AssetsDirective extends Directive {
	private String fileName;
	
	@Override
	public void setExprList(ExprList exprList) {
		Expr[] exprArray = exprList.getExprArray();
		if (exprArray.length == 0) {
			throw new ParseException("#assets directive parameter cant not be null", location);
		}
		if (exprArray.length > 1) {
			throw new ParseException("wrong number of #assets directive parameter, one parameters allowed at most", location);
		}
		if (!(exprArray[0] instanceof Const)) {
			throw new ParseException("#assets first parameter must be constant", location);
		}
		this.fileName = ((Const)exprArray[0]).getStr();
	}

	@Override
	public void exec(Env env, Scope scope, Writer writer) {
		try {
			String path = AssetsUtils.getPath(fileName);
			write(writer, path);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
